<?php
// ini_set('display_errors',1);
// error_reporting(E_ALL);
/**
 * USER MANAGER CLASS 
 * PDO SAFE
 * @author HxBreak
 * @Description: ...
 * @Date 2017年6月7日 上午12:18:55 
 * @File UserManager.php
 */

require '../vendor/autoload.php';
require '../common.php';
require 'Mail.php';

use Base64Url\Base64Url;

class UserManager{

private $sqluser;
private $sqlpass;
private $sqlurl;
private $conn;
// public function connectDatabase(){
//     $this->conn = mysql_connect($this->sqlurl, $this->sqluser, $this->sqlpass);
//     if(!$conn){，
//         echo('ERROR:UserManager Class Cannot Instance');
//     }else{
//         mysql_select_db('connect', $conn);
//     }
// }
public function __construct (){
/* 	$this->sqluser = 'admin8X4yygd';
	$this->sqlpass = 'YJNz4Jdpnb8h';
    $this->sqlurl = 'localhost:3306';

    $this->conn = mysql_connect($this->sqlurl, $this->sqluser, $this->sqlpass);
    if($this->conn){
        echo(mysqli_connect_error());
        mysql_select_db('connect');
    }else{
        echo("ERROR:CAN\'T CONNECT TO DATEBASE");
    }
 */    
	$this->dbc = pdo_root_connect();
}
#localhost:3306 admin8X4yygd YJNz4Jdpnb8h
/* public function isConnected(){
    return $conn;
} */
/**
 * 检查用户是否已经存在
 * @param 用户名 $username
 * @return boolean
 */
public function lookupUser($username){
    //createtime + 60 * 60 * 2 >= currenttime 100000 + 7200 >= 107203
	$intime = time() - 60 * 60 * 2;
	$stmt1 = $this->dbc->prepare('select * from userinfo where username=:username');
	$stmt1->bindParam(':username', $username);
	$stmt1->execute();
	
	$stmt2 = $this->dbc->prepare('select * from verifying where username=:username and
	createat>(unix_timestamp(now()) - (60*60*2)) and
	status=1');
	$stmt2->bindParam(':username', $username);
	$stmt2->execute();
//    $query = mysql_query("select * from userinfo where username='$username'");
//    $query2 = mysql_query("select * from verifying where username='$username' and createat>'$intime' and status='1'");
	return $stmt1->rowCount() > 0 || $stmt2->rowCount() > 0;
}
/*检查是否该邮箱已经注册过账号
*/
public function lookupEmail($email){
    if(!checkEmail($email)){
        //邮件格式不匹配返回真
        return true;
    }
    $stmt = $this->dbc->prepare('select * from userinfo where email=:email');
    $stmt->bindParam(':email', $email);
    $stmt->execute();
    return $stmt->rowCount() > 0;
//    $query = mysql_query("select * from userinfo where email='$email'");
/*     if($query){
        $num = mysql_num_rows($query);
        mysql_free_result($query);
        //返回可用的行数，未找到会返回false        
        return $num;
    }else{
        //语句执行失败
        return true;
    }
 */
}

/*
*检查用户密码
*/
public function checkUserWithPass($username, $password){
    $stmt = $this->dbc->prepare('select * from userinfo where username=? and password=?');
    $stmt->execute(array($username, $password));
    return $stmt->rowCount() > 0;
}
//使用用户名和token检查用户
public function checkUserWithToken($username, $token){
	$stmt = $this->dbc->prepare('select * from userinfo where username=? and token=?');
	$stmt->execute(array($username, $token));
	return $stmt->rowCount() > 0;
}
//为用户生成新的token
public function buildToken($username){
    $t_token = uniqid('ac_'.$username);
    return substr(md5($t_token), 8, 16);
}

//基础方法 字符串长度大于5，小于17(6-16)
public function checkStringLength($str){
    return ((strlen($str) > 5 ) && (strlen($str) < 17));
}
//检查字符串是否合法
public function checkString($str){
    $pattern = "/^[_a-zA-Z0-9]*$/";
    return preg_match($pattern, $str);
}
public function matchPassword($password){
    ///^[\w\-\=\[\]\;\,\.\/\~\!@#\$\%\^\*\(\)\_\+\{\}]*$/
    $pattern = '/^[\w\-\=\[\]\;\,\.\/\~\!@#\$\%\^\*\(\)\_\+\{\}]*$/';
    return preg_match($pattern, $password);
}
public function updateUserToken(){

}
public function createUser(){

}
public function insertVerifyUser($username, $password, $email){
    if($this->checkString($username) 
        && $this->checkStringLength($username)
        && $this->checkStringLength($password)
        && $this->matchPassword($password)
        && ! $this->lookupUser($username)
        && ! $this->lookupEmail($email)
     ) {   //信息检查通过
            $vcode = $this->buildToken($username);           
            $time = time();
            $password = Base64Url::encode($password);
            $stmt = $this->dbc->prepare('insert into verifying (email, username, password, vcode, createat, status) values
			(?, ?, ?, ?, unix_timestamp(now()), 1)');
            $stmt->execute(array($email, $username, $password, $vcode));
            if($stmt->rowCount() == 0){
            	return false;
            }
            //$query = mysql_query("insert into verifying (email, username, password, vcode, createat, status) values('$email', '$username', '$password', '$vcode', '$time', '1')");
        	//send Email to user
            $this->sendMailToUser($username, $email, $vcode);
            return true;
        }else{
            return false;
        }
}
public function insertUser($vcode){
    if(!$this->checkString($vcode)){
    	return false;
    }
    $stmt = $this->dbc->prepare('select * from verifying where vcode=? and status=1 and createat>unix_timestamp( DATE_SUB(now() ,INTERVAL 2 HOUR))');
    $stmt->execute(array($vcode));
//    $verify = mysql_query("select * from verifying where vcode='$vcode' and status='1' and createat>'$intime'");
    if($row = $stmt->fetch()){
//		mysql_query("update verifying set status='2' where vcode='$vcode'");
		if($this->dbc->exec("update verifying set status='2' where vcode='$vcode'") > 0){
		$username = $row['username'];
		$password = $row['password'];
		$email = $row['email'];

		$stmt2 = $this->dbc->prepare('insert into userinfo (username, password, email, createat) value (?, ?, ?, unix_timestamp(now()))');
		$stmt2->execute(array($username, $password, $email));
		echo json_encode($stmt2->errorInfo());
		echo "$username $password $email";
		return $stmt2->rowCount() > 0;
		}
    }
    return false;
}
public function sendMailToUser($username, $email, $vcode){
    $from = 'hxbreak@qq.com'; //change this to your email address
    $to = $email; // change to address
    $subject = '欢迎您在 N (Near By) 社区进行注册'; // subject of mail
    $body = "如果你正在 N 社区进行注册用户: $username 请点击下面的链接完成验证过程"
    ."\r\n https://connect-hxbreak.rhcloud.com/account/register.php?action=checkcode&ticket=$vcode"
    .' #不要回复此邮件'; //content of mail

    $headers = array(
            'From' => $from,
            'To' => $email,
            'Subject' => $subject
    );

    $smtp = Mail::factory('smtp', array(
            'host' => 'ssl://smtp.qq.com',
            'port' => '465',
            'auth' => true,
            'username' => 'hxbreak@qq.com', //your gmail account
            'password' => 'tvggcgodqziebacg' // your password
    ));

    if (PEAR::isError($e = $mail = $smtp->send($to, $headers, $body))) {
        return false;
    }else{
        return true;
    }
}
}
?>